package com.itheima.springboot_reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.springboot_reggie.common.ApplicationContext;
import com.itheima.springboot_reggie.common.R;
import com.itheima.springboot_reggie.emtity.ShoppingCart;
import com.itheima.springboot_reggie.service.IShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private IShoppingCartService shoppingCartService;


    /**  接口一：添加购物车
     *   请求url地址：/shoppingCart/add
     * 请求方式：POST
     * 请求参数：JSON格式的数据，
     * 响应结果【格式统一】：R<ShoppingCart>
     */
    @PostMapping("/add")
    public R <String> addShoppingCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){

            /* 菜品或者套餐是否点过
     如何知道烧鹅被点过了？？ 根据烧鹅的菜品id，查询下数据库中有没有烧鹅这个数据
     如何是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
     如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?
     */

        //创建条件构造器
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getId,ApplicationContext.getId());

        //判断当前用户点的是菜品还是套餐
        Long dishId = shoppingCart.getDishId();
        if (dishId!=null){
            //如果是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
            //不为空，说明点的是菜品（添加到购物车的是菜品）
            wrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else {
            //如果不是菜品，那么点的一定是套餐（添加到购物车的是套餐）
            //如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?
            wrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        //查询当前菜品或者套餐是否在购物车中
        //Sql:select * from shopping_cart where user_id = ? and dish_id/setmeal_id = ?
        ShoppingCart queryShoppingCart = shoppingCartService.getOne(wrapper);
        //第一次点的时候是新增，后面再点击的时候是修改
        if(queryShoppingCart != null){
            //如果已经存在，则是更新，在原来的数量基础上加一
            Integer number = queryShoppingCart.getNumber();
            queryShoppingCart.setNumber(number +1);
            shoppingCartService.updateById(queryShoppingCart);

        }else {
            //如果是不存在，则是新增，添加到购物车中，数量默认就是1
            //设置 number=1
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(ApplicationContext.getId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        }
        return R.success("添加购物车成功");
    }

     /**    查询 购物车列表
      *   注意： 需要封装的结果R中的Data数据是：购物车列表数据  List<ShoppingCart>
      *
      *   请求url地址：/shoppingCart/list
      * 请求方式：GET
      * 请求参数：无
      * 响应结果【格式统一】：R<List<ShoppingCart>>
      *
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        log.info("查看购物车...");

        //在ShoppingCartController中创建list方法，
        // 根据当前登录用户ID查询购物车列表，并对查询的结果进行创建时间的倒序排序。
        //创建条件构造器
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, ApplicationContext.getId());
        wrapper.orderByAsc(ShoppingCart::getCreateTime);

        List<ShoppingCart> list = shoppingCartService.list(wrapper);

        return R.success(list);
    }

    /**   接口三：取消购物车
     * 请求url地址：/shoppingCart/sub
     * 请求方式：POST
     * 请求参数：JSON格式的数据，ShoppingCart接收
     *响应结果【格式统一】：R<ShoppingCart>
     */
    @PostMapping("/sub")
    public R<ShoppingCart> removeSubShoppingCart(@RequestBody ShoppingCart shoppingCart){

        log.info("removeSubShoppingCart()....");

        //菜品或者套餐id 查询出当前ShoppingCart数据
        // 如何是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
        // 如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?

         //菜品或者套餐是否点过
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, ApplicationContext.getId());
         // 判断当前用户点的是菜品还是套餐
        if (shoppingCart.getDishId() != null) {//是菜品
            //如果是菜品：select * from shopping_cart where dish_id = ? and user_id = ?
            wrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
        } else {
            //如果不是菜品，那么一定是套餐
            //如果是套餐：select * from shopping_cart where setmeal_id = ? and user_id = ?
            wrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
        }
        ShoppingCart queryShoppingCart = shoppingCartService.getOne(wrapper);
         // (设置 number-1) 然后操作：
        Integer number = queryShoppingCart.getNumber() - 1;
        queryShoppingCart.setNumber(number);
        //update shopping_cart set number = ? where id = ?
        if (number > 0) {
            // >0， update更新  update set number=? where id = ?
            shoppingCartService.updateById(queryShoppingCart);
        }else {
            //<=0,如何操作 delete from shopping_cart where dish_id = ? and user_id = ?
            shoppingCartService.remove(wrapper);
        }
        return R.success(shoppingCart);

    }

    /**    接口四：清空购物车
     * 请求url地址：/shoppingCart/clean
     * 请求方式：DELETE
     * 请求参数：无
     * 响应结果【格式统一】：R<String>
     */
    @DeleteMapping("/clean")
    public R<String> deleteShoppingCart(){

        //先查询所有，再删除
        // 根据当前用户id进行删除：delete from shoping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,ApplicationContext.getId());

        shoppingCartService.remove(wrapper);
        return R.success("清空购物车成功");

    }















}
